<template>
  <div style="margin-left: auto">
    <p>采购退货单新增</p>
  </div>
  <div style="right: auto">
    <span style="float: right">
      <el-button type="primary" @click="addPurchaseInvoice">保存</el-button>
      <el-button type="Default" @click="">取消</el-button>
      <el-button
        style="
          background-color: aquamarine;
          border-color: aquamarine;
          color: white;
        "
        :disabled="!isAddSuccess"
        @click="Examineandapprove"
        >审核</el-button
      >
      <el-button type="info" @click="">反审核</el-button>
    </span>
  </div>
  <hr />
  <el-scrollbar style="height: 320px; color: dimgray">
    <div class="scrollbar-flex-content">
      <p class="scrollbar-demo-item">
        <el-form :inline="true" :model="form" class="demo-form-inline">
          <el-form-item label="单据编码：" style="width: 308px">
            <el-input v-model="form.purchaseReturnOrderNo" :disabled="true" />
          </el-form-item>
          <el-form-item label="单据日期" style="width: 308px">
            <el-date-picker
              v-model="form.documentDate"
              type="date"
              placeholder="Pick a date"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="单据状态" style="width: 308px">
            <input v-model="form.documentsStatus" :disabled="true" />
          </el-form-item>
          <el-form-item label="业务状态" style="width: 308px">
            <el-select
              v-model="form.businessStatus"
              placeholder="请选择"
              clearable
            >
              <el-option label="正常" value="1" />
              <el-option label="挂起" value="2" />
              <el-option label="手工关闭" value="3" />
              <el-option label="系统关闭" value="4" />
            </el-select>
          </el-form-item>
        </el-form>

        <el-form :inline="true" :model="form" class="demo-form-inline">
          <el-form-item label="业务类型" style="width: 308px">
            <el-select
              v-model="form.businessType"
              placeholder="请选择"
              clearable
            >
              <el-option label="零部件发票" value="1" />
              <el-option label="原材料发票" value="2" />
              <el-option label="五金发票" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作员" style="width: 308px">
            <el-input v-model="form.operator" :disabled="true" />
          </el-form-item>
          <el-form-item label="审核员" style="width: 308px">
            <el-input v-model="form.audit" :disabled="true" />
          </el-form-item>
          <el-form-item label="审核日期" style="width: 308px">
            <el-date-picker
              type="date"
              placeholder="Pick a date"
              v-model="form.auditDate"
              style="width: 100%"
              :disabled="true"
            />
          </el-form-item>
        </el-form>

        <el-form
          :inline="true"
          style="margin-top: 50px"
          :model="form"
          class="demo-form-inline"
        >
          <el-form-item label="采购单号" style="width: 308px">
            <el-input v-model="form.purchaseOrderNo" />
          </el-form-item>
          <el-form-item label="供应商" style="width: 308px">
            <el-input v-model="form.supplier" />
          </el-form-item>
          <el-form-item label="退货仓库" style="width: 308px">
            <el-select
              v-model="form.returnsWarehouse"
              placeholder="Select"
              size="large"
              style="width: 240px"
            >
              <el-option label="成品仓" value="1" />
              <el-option label="半成品仓" value="2" />
              <el-option label="零部件仓" value="3" />
              <el-option label="原料仓" value="4" />
              <el-option label="五金仓" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="退货原因" style="width: 308px">
            <el-select
              v-model="form.reasonForReturn"
              placeholder="Select"
              size="large"
              style="width: 240px"
            >
              <el-option label="无" value="1" />
              <el-option label="外观问题" value="2" />
              <el-option label="性能问题" value="3" />
            </el-select>
          </el-form-item>
        </el-form>

        <el-form
          :inline="true"
          style="margin-top: 50px"
          :model="form"
          class="demo-form-inline"
        >
          <el-form-item label="备注信息" style="width: 308px">
            <el-input v-model="form.descInfo" type="textarea" />
          </el-form-item>
        </el-form>
      </p>
    </div>
  </el-scrollbar>
  <div style="float: right">
    <el-button type="warning" @click="dialogTableVisibleDHD = true"
      >¼ 引入</el-button
    >
  </div>

  <table style="border-collapse: collapse">
    <tr>
      <td style="width: 90px">序号</td>
      <td style="width: 90px">跟单编号</td>
      <td style="width: 90px">物料编码</td>
      <td style="width: 90px">物料名称</td>
      <td style="width: 90px">型号规格</td>
      <td style="width: 90px">主计量</td>
      <td style="width: 90px">批号</td>
      <td style="width: 90px">数量</td>
      <td style="width: 90px">出库数量</td>
      <td style="width: 90px">退货说明</td>
      <td style="width: 90px">操作</td>
    </tr>
    <tr v-for="(ruleForm, index) in loge.healthArray">
      <td style="width: 90px">
        {{ ruleForm.purchaseReturnOrderSubtableId
        }}<!-- 序号 -->
      </td>
      <td style="width: 90px">
        {{ ruleForm.copyNo
        }}<!-- 跟单号 -->
      </td>
      <td style="width: 90px">
        {{ ruleForm.materialNo
        }}<!-- 物料编码 -->
      </td>
      <td style="width: 90px">
        {{ ruleForm.materialName
        }}<!--物料名称  -->
      </td>
      <td style="width: 90px">
        {{ ruleForm.logisticsCode
        }}<!-- 型号规格 -->
      </td>
      <td style="width: 90px">
        {{ ruleForm.masterMetering }}
        <!-- 主计量 -->
      </td>
      <td style="width: 90px">
        <el-input
          type="text"
          style="width: 90px"
          v-model="ruleForm.lotNumber"
        ></el-input
        ><!-- 批号 -->
      </td>
      <td style="width: 90px">
        {{ ruleForm.num
        }}<!-- 数量 -->
      </td>
      <td style="width: 90px">
        {{
        }}<!-- 出库数量 -->
      </td>
      <td style="width: 90px">
        <el-input
          style="width: 90px"
          v-model="ruleForm.modelSpecifications"
        ></el-input>
        <!-- 退货说明 -->
      </td>
      <td style="width: 90px">
        <el-button type="danger" link @click="del">删除</el-button>
      </td>
    </tr>
  </table>

  <div>
    <el-dialog v-model="dialogTableVisibleDHD" title="采购到货单" width="1000">
      <el-table
        :data="suppliers"
        stripe
        style="width: 100%"
        v-show="suppliers.length != 0"
      >
        <el-table-column prop="purchasedGoodsId" label="序号" />
        <el-table-column prop="receiptNum" label="跟单编号" />
        <el-table-column prop="receiptState" label="单据状态" />
        <el-table-column prop="system" label="供应商" />
        <el-table-column prop="materialName" label="物料名称" />
        <el-table-column prop="materialCode" label="物料编码" />
        <el-table-column prop="quantity" label="到货数量" />
        <el-table-column prop="receiptDate" label="单据日期">
          <template #default="scope">
            {{ scope.row.receiptDate.substring(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column label="退货数量">
          <template #default="scope">
            <el-input
              :max="scope.row.quantity"
              v-model="scope.row.inputValue"
              @input="validateReturnQuantity(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <template #footer v-slot="scope">
        <div class="dialog-footer">
          <el-button @click="dialogTableVisibleDHD = false">Cancel</el-button>
          <el-button type="primary" :disabled="!isValid" @click="submitForm"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import Cookie from 'cookies-ts';
import axios from 'axios';
import { number } from 'echarts';
import { Plus, Download, Upload, List } from '@element-plus/icons-vue';
const dialogTableVisibleWl: any = ref(false);
const dialogTableVisibleDHD: any = ref(false);
const formLabelWidth = '140px';
const apiurls = import.meta.env.VITE_APP_API_URL_BasicInformationCommon;//5176
const bpiurls = import.meta.env.VITE_APP_API_URL_BasicInformationWrite;//5013
const cpiurls = import.meta.env.VITE_APP_API_URL_RBACCommon;//5214
const dpiurls = import.meta.env.VITE_APP_API_URL_RBACWrite;//5268
const epiurls = import.meta.env.VITE_APP_API_URL_SalesManagementCommon;//5227
const fpiurls = import.meta.env.VITE_APP_API_URL_SalesManagementWrite;//5020
const isAddSuccess =ref(false)//初始状态为未新增成功
const cookie = new Cookie()
onMounted(() => {
  GetSuppliers();
});

const form = reactive({
  purchaseReturnOrderId: '',
  purchaseReturnOrderNo: '',
  purchaseReturnOrderSerialNumber: 0,
  businessType: '',
  purchaseOrderNo: '',
  descInfo: '',
  documentDate: '',
  operator: 'liy',
  supplier: '',
  documentsStatus: 1,
  audit: '',
  returnsWarehouse: '',
  businessStatus: '',
  auditDate: null,
  reasonForReturn: 0,
});

const numbers = ref(0);
const loge: any = reactive({
  healthArray: <any>[
    reactive({
      purchaseReturnOrderSubtableId: numbers.value + 1,
      copyNo: '',
      materialNo: '',
      materialName: '',
      modelSpecifications: '',
      masterMetering: '',
      lotNumber: '',
      num: 0,
      outboundShipmentsNum: 0,
      returnInstructions: '',
      purchaseReturnOrderSerialNumber: ''
    })
  ]
});
// //新增行
// const addMaterial = () => {
//   loge.healthArray.push(
//     reactive({
//       materialId: loge.healthArray.length + numbers.value,
//       purchaseON: '手工单据',
//       warehouse: '手工单据',
//       inventoryRN: '手工单据',
//       logisticsCode: '',
//       nameOfLogistics: '',
//       modelSpecification: '',
//       mainMetering: 0,
//       num: 0,
//       price: 0,
//       amount: 0,
//       taxRate: 0,
//       amountOfTax: 0,
//       serialNumber: ''
//     })
//   );
// };
//删除行
const del = () => {
  loge.healthArray.splice(loge.healthArray.length - 1, 1);
  ElMessage.warning({
    message: '删除成功'
  });
};

const index1 = ref(0);
const xuanz = (index: any) => {
  dialogTableVisibleWl.value = true;
  index1.value = index;
};


const addPurchaseInvoice = () => {
  let request: any = ref([{
    purchaseReturnOrderSubtableId: 0,
    copyNo: '',
    materialNo:'',
    materialName:'',
    lotNumber:'',
    num: 0,
    outboundShipmentsNum: 0,
    returnInstructions: '',
    purchaseReturnOrderSerialNumber:''
  }]);
  console.log(request);
  request = loge.healthArray;
  console.log(request);
  var datas = {
    purchaseReturnOrderNo: form.purchaseReturnOrderNo,
    purchaseReturnOrderSerialNumber:'',
    businessType: form.businessType,
    purchaseOrderNo: form.purchaseOrderNo,
    descInfo: form.descInfo,
    documentDate: form.documentDate,
    operator: form.operator,
    supplier: form.supplier,
    documentsStatus: form.documentsStatus,
    audit: form.audit,
    returnsWarehouse: form.returnsWarehouse,
    businessStatus: form.businessStatus,
    auditDate: form.auditDate,
    reasonForReturn: form.reasonForReturn,
    purchaseReturnOrderSubtableDtos:request
  };
  console.log(datas.supplier);

  axios
    .post(
      fpiurls+'/api/SalesManagementWrite/PurchaseReturnOrderCreate',datas)
    .then((res) => {
      if (res.data.code == 0) {
        ElMessage.success(res.data.msg);
        isAddSuccess.value = true
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};

var employeeName =cookie.get('employeeName')
 console.log(employeeName,123456);
 
//审核参数
const Examineand = reactive({
  workid:3,
  username:employeeName,
  uSerid:1,
  workType:1,
  gnumid:'CGFP20240106'
})




//审批流程
const Examineandapprove=()=>{
  axios.post('http://localhost:5020/api/SalesManagementWrite/ProcessFlowEngineHandle',Examineand).then(res=>{
    if(res.data.code==1)
    {
      ElMessage.success(res.data.msg)
      if(res.data.msg=='审批成功')
      {
        form.documentsStatus=1
      }
      else if(res.data.msg=='撤销成功')
      {
        form.documentsStatus=0
      }

    }
  }).then(err=>{

  })
}

const formInline = reactive({
  pageIndex: 1,
  pageSize: 10,
  pageCount: 0,
  totalCount: 0
});

//销售订单单据列表
const suppliers: any = ref([]);
const GetSuppliers = () => {
  axios
    .get(apiurls+'/api/Suppliers/PurchasedGoodsList', {
      params: {
        pageIndex: formInline.pageIndex,
        pageSize: formInline.pageSize
      }
    })
    .then((res) => {
      console.log(res.data.data);
      // 遍历数据并添加新字段
      const updatedSuppliers = res.data.data.list.map((item: any) => {
        return {
          ...item,
          inputValue: 0
        };
      });
      suppliers.value = updatedSuppliers;
      formInline.pageCount = res.data.data.totalPage;
      formInline.totalCount = res.data.data.totalCount;
    })
    .catch((err) => {
      console.log(err);
    });
};
const isValid = ref(false);
// 验证输入的退货数量是否大于到货数量
const validateReturnQuantity = (row: any) => {
  if (row.inputValue > row.quantity) {
    row.inputValue = row.quantity;
    ElMessage.warning('退货数量不能大于到货数量');
    isValid.value = suppliers.every(
      (item: any) => item.inputValue !== '' && !isNaN(item.inputValue)
    );
  }
  if (!isNaN(row.inputValue)) {
    isValid.value = true; // 启用按钮
  } else {
    isValid.value = false; // 禁用按钮
  }
};
console.log(suppliers, 2222);
//确定按钮
const submitForm = () => {
  const validRows = suppliers.value.filter((item: any) => {
    return item.inputValue <= item.quantity && item.inputValue > 0;
  });
  console.log(validRows, 445455);
  if (validRows.length > 0) {
    localStorage.setItem('validRows', JSON.stringify(validRows));
    let index = 1;
    loge.healthArray = validRows.map((item: any) => {
      form.purchaseOrderNo = item.receiptNum;
      form.supplier = item.system;
      return {
        purchaseReturnOrderSubtableId: index++,
        copyNo: item.receiptNum || '', //跟单编号
        materialNo: item.materialCode || '', //物料编码
        materialName: item.materialName || '', //物料名称
        modelSpecifications: item.typeSpecification || '', //型号规格
        masterMetering: item.documentType || '', //主计量
        num: item.inputValue || 0 // 数量
      };
    });

    dialogTableVisibleDHD.value = false;
    ElMessage.success('成功保存有效行数据');
  } else {
    ElMessage.warning('没有符合条件的行数据');
  }
  dialogTableVisibleDHD.value = false;
};
</script>

<style scoped>
.scrollbar-flex-content {
  display: flex;
}

.scrollbar-demo-item {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1800px;
  height: 300px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
}
</style>
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
  border-top: 1px solid #ccc;
  /* 设置顶部边框为3px宽度的红色 */
  padding: 10px;
  text-align: center;
}

/* 设置 td 的样式 */

table td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: center;
  font-size: 14px;
  height: 60px;
  width: 150px;
  white-space: nowrap;
  /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

/*______________________________________________________*/

.table-container {
  max-width: 100%;
  overflow-x: auto;
  /* 启用水平滚动 */
  margin: 20px 0;
  /* 设置容器的外边距 */
}

/* :deep(.el-input__wrapper) {
  box-shadow: none;
  text-align: center;
}

:deep(.el-select__wrapper) {
  box-shadow: none;
}

::v-deep(.center-input .el-input__inner) {
  text-align: center;
} */
</style>

<style scoped>
.upload-demo {
  display: inline-block;
  width: 100%;
}
</style>
